package com.e100;

import com.base.util.BaseIOUtils;
import com.base.util.FileUtils;
import com.base.util.HttpClient;
import com.common.FileController;
import com.common.util.AccessUtil;
import com.common.util.AjaxMessageUtil;
import com.e100.bean.E100NormalResponse;
import com.e100.bean.E100PartResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/e100")
public class E100Controller extends FileController{

    @Value("${e100.saveLocation}")
    private String savePath;

    @Value("${file.saveLocation}")
    private String rootPath;


    @RequestMapping("/detail")
    public Object redirectRequest(@RequestBody String url) throws Exception{
        if(StringUtils.isBlank(url)){
            return AjaxMessageUtil.createErrorMessage("无效的URL请求",null);
        }
        Object response = null ;
        //课文
        if(url.endsWith(".ett")){
            response = savePart(url);
        }
        //普通内容
        else if(url.endsWith(".etc")){
            response = saveNormal(url);
        }
        return AjaxMessageUtil.createInfoMessage("SUCCESS",response);
    }

    private E100NormalResponse saveNormal(String url) throws Exception{
        E100NormalResponse e100Response;
        File f = downloadFile(url);
        File []fChilds = f.listFiles();
        AccessUtil.accessSuccess(fChilds!=null&&fChilds.length>0,"获取文件缓存时出错！");
        //组装文件数据
        e100Response = new E100NormalResponse();
        Map<String,String> names = new HashMap<>();
        e100Response.setTextNames(names);
        for(File file:fChilds){
            if(file.getName().toUpperCase().endsWith(".INI")){
                e100Response.setConfig(BaseIOUtils.readSmallTextFileToString(file,"UTF-8"));
            }else{
                names.put(file.getName().substring(0,file.getName().lastIndexOf(".")),getResourceUrl(file));
            }
        }
        return e100Response;
    }

    private E100PartResponse savePart(String url) throws Exception{
        E100PartResponse e100Response;
        File f = downloadFile(url);
        File []fChilds = f.listFiles();
        AccessUtil.accessSuccess(fChilds!=null&&fChilds.length>0,"获取文件缓存时出错！");
        //组装文件数据
        e100Response = new E100PartResponse();
        for(File file:fChilds){
            if(file.getName().toUpperCase().endsWith(".TXT") || file.getName().toUpperCase().endsWith(".ETE")){
                e100Response.setText(BaseIOUtils.readSmallTextFileToString(file,"UTF-8"));
            }else if(file.getName().toUpperCase().endsWith(".INI")){
                e100Response.setConfigInfo(BaseIOUtils.readSmallTextFileToString(file,"UTF-8"));
            }else{
                e100Response.setAudioUrl(getResourceUrl(file));
            }
        }
        return e100Response;
    }

    private File downloadFile(String url) throws Exception{
        //这是保存的子目录，在请求资源之前先检查文件是否存在
        String childFoldName = FileUtils.getHash(url.substring(url.lastIndexOf("/")+1),"MD5");
        //文件保存的根目录
        String realSavePath=rootPath+"/"+savePath;
        File f = new File(realSavePath+"/"+childFoldName);
        //检查磁盘缓存
        if(!f.exists()){
            f.mkdirs();
            HttpClient.clearAll();
            HttpClient.addHead(HttpClient.HEAD_USER_AGENT,HttpClient.AGENT_CHROME_HEAD);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            HttpClient.request(url,null,bos);
            //文件解压：（由于文件都是小文件，可以直接放在内存中解压）
            BaseIOUtils.unzipFromInputStream(new ByteArrayInputStream(bos.toByteArray()),f.getAbsolutePath());
        }
        AccessUtil.accessSuccess(f.isDirectory(),"获取文件缓存时出错！");
        return f;
    }

    private String getResourceUrl(File file){
        return "resource?id="+file.getAbsolutePath().replaceAll("\\\\","/").substring(rootPath.length());
    }



    @RequestMapping("/upfile")
    @ResponseBody
    public Object upFiles(@RequestParam("upfile[]") MultipartFile[] multipartFile){
        if(multipartFile!=null && multipartFile.length>0){
            for(MultipartFile f:multipartFile){
                System.out.println(f.getName()+"  "+f.getOriginalFilename());
            }
        }
        return null;
    }
}
